<template>
  <div :style="popupPosition" class="absolute">
    <q-popup-proxy v-model="amrPanel.visible" :offset="[15, 0]" anchor="center end" breakpoint="0"
                   class="bg-grey-1 q-pa-md overflow-hidden shadow-8" no-parent-event self="center left"
                   style="width: 35rem;" transition-hide="jump-left" transition-show="jump-right">
      <q-item v-drag class="text-grey-8 text-h6 text-weight-bold q-pt-none">
        <q-item-section class="col-auto no-margin">
          <div class="row items-center no-wrap justify-center">
            <q-badge :color="colorInfo.color || 'negative'" class="q-badge-dot q-mr-xs" rounded />
            <span class="text-subtitle1">{{ colorInfo.label || $t('Unknown') }}</span>
          </div>
        </q-item-section>
        <q-item-section>
          <div class="row items-center no-wrap justify-center">
            <q-img :ratio="1" :src="AMRImg" width="3rem"></q-img>
            <div class="column no-wrap text-body1 text-bold text-dark q-pl-xs">
              <span>{{ taskInfo.agvBrandCode }}</span>
              <span>{{ taskInfo.agvCode }}</span>
            </div>
          </div>
        </q-item-section>
        <q-item-section class="col-auto no-margin">
          <div class="row items-center no-wrap justify-center">
            <q-icon size="2rem" v-bind="batteryAttrs" />
            <span>{{ taskInfo.battery || 0 }}%</span>
          </div>
        </q-item-section>
      </q-item>
      <q-separator class="q-mb-sm"></q-separator>
      <q-item v-for="(column, index) in columns" :key="index" class="items-center q-px-sm q-py-xs">
        <template v-for="col in column" :key="col.value">
          <q-item-section class="text-caption text-grey-6 text-right ellipsis col-auto">
            <div class="header-label">{{ col.label }}:</div>
          </q-item-section>
          <q-item-section v-if="col.value === 'taskCode'" class="cursor-pointer text-primary" @click.stop="handleTask">
            <qx-tooltip>{{ formatLabel(col) }}</qx-tooltip>
          </q-item-section>
          <q-item-section v-else>
            <qx-tooltip>{{ formatLabel(col) }}{{ col.unit || '' }}</qx-tooltip>
          </q-item-section>
        </template>
      </q-item>
      <q-separator class="q-mt-sm"></q-separator>
      <div class="row q-gutter-sm q-pt-md items-center justify-around no-wrap">
        <q-btn v-bind="btnAttrs"
               @click="handleDispatch('/yfagv/api/mainBusinessLevel3/ctrl/stopAgv', undefined, 'pause')">
          {{ $t('TaskCore.Pause') }}
        </q-btn>
        <q-separator class="q-mt-md q-mb-sm rounded-borders" color="grey-4" vertical></q-separator>
        <q-btn v-bind="btnAttrs"
               @click="handleDispatch('/yfagv/api/mainBusinessLevel3/ctrl/resumeAgv', undefined, 'unPause')">
          {{ $t('TaskCore.Resume') }}
        </q-btn>
        <q-separator class="q-mt-md q-mb-sm rounded-borders" color="grey-6" vertical></q-separator>
        <q-btn v-bind="btnAttrs" @click="handleCancel">
          {{ $t('TaskCore.CancelTask') }}
        </q-btn>
        <q-separator class="q-mt-md q-mb-sm rounded-borders" color="grey-4" vertical></q-separator>
        <q-btn v-bind="btnAttrs" @click="handleNext">
          {{ $t('TaskCore.ContinueTask') }}
        </q-btn>
      </div>
      <div class="row q-gutter-sm q-pt-md items-center justify-around no-wrap">
        <q-group v-model="execForm.moveObjectType" :options="groupOptions" class="row no-wrap text-no-wrap" dense inline
                 type="radio"></q-group>
        <q-input ref="startInputRef" v-model="execForm.startPosition" :placeholder="`${startExecName}`"
                 :rules="[val =>!!val || '']" class="items-center non-field__bottom no-padding" dense no-error-icon
                 outlined @keydown.enter="handleMove"></q-input>
        <q-input ref="endInputRef" v-model="execForm.endPosition" :placeholder="`${endExecName}`"
                 :rules="[val =>!!val || '']" class="items-center non-field__bottom no-padding" dense no-error-icon
                 outlined @keydown.enter="handleMove"></q-input>
        <q-input ref="codeInputRef" v-model="execForm.rcsTaskType" :placeholder="`${$t('TaskCore.TaskTemplateCode')}`"
                 :rules="[val =>!!val || '']" class="items-center non-field__bottom no-padding" dense no-error-icon
                 outlined @keydown.enter="handleMove">
          <template v-slot:after>
            <q-btn v-bind="btnAttrs" @click="handleMove">{{ $t('TaskCore.ExecTask') }}</q-btn>
          </template>
        </q-input>
      </div>
      <q-inner-loading :showing="loading">
        <q-spinner-ios color="primary" size="3rem"></q-spinner-ios>
      </q-inner-loading>
    </q-popup-proxy>
  </div>
  <AMRTaskPanel v-model="modalVisible" :taskCode="taskCode"></AMRTaskPanel>
</template>

<script setup>
import { i18n } from 'boot/i18n.js'
import { date } from 'quasar'
import { postAPI } from 'src/api/index.js'
import { AGVStatus } from 'src/enum'
import { createDialog, createSuccessTips } from 'src/utils/utils.js'
import { amrPanel } from 'src/views/MapCore/MapGlobal/utils/KonvaEvent.js'
import { formatAMRImage } from 'src/views/MapCore/MapGlobal/utils/utils.js'
import AMRTaskPanel from 'src/views/MapCore/Monitoring/Panel/AMRTaskPanel.vue'
import { computed, onUnmounted, ref, watch } from 'vue'

const taskCode = ref('')
const loading = ref(false)
const popupPosition = ref({})
const endInputRef = ref(null)
const codeInputRef = ref(null)
const startInputRef = ref(null)
const modalVisible = ref(false)
const execForm = ref({ moveObjectType: '10' })
const btnAttrs = {
  color: 'primary', outline: true, padding: '.5rem .75rem', noWrap: true, class: 'text-caption text-weight-medium'
}
const taskInfo = computed(() => amrPanel.value.amrInfo || {})
const batteryAttrs = computed(() => {
  const { battery = 0 } = taskInfo.value
  const color = battery < 20 ? 'negative' : 'positive'
  const batteryValue = Math.round(Number(battery) / 10) * 10
  if (batteryValue < 10) return { name: 'mdi-battery-outline', color }
  if (batteryValue > 90) return { name: 'mdi-battery', color }
  return { name: `mdi-battery-${batteryValue}`, color }
})
const AMRImg = computed(() => {
  const { amrStatus = '', agvTypeCode: amrType } = taskInfo.value
  return formatAMRImage(amrStatus, amrType)
})
const groupOptions = computed(() => {
  return [{
    label: i18n.t('CarrierCore.Rack'), value: '10'
  }, {
    label: i18n.t('CarrierCore.Container'), value: '20'
  }]
})
const colorInfo = computed(
  () => AGVStatus.value.find(item => item.value === taskInfo.value.statusClassNumberCode) || {})
const startName = computed(
  () => i18n.t(taskInfo.value.moveObjectType === '20' ? 'CarrierCore.StartSlotCode' : 'MapCore.StartStation'))
const endName = computed(
  () => i18n.t(taskInfo.value.moveObjectType === '20' ? 'CarrierCore.EndSlotCode' : 'MapCore.EndStation'))
const startExecName = computed(
  () => i18n.t(execForm.value.moveObjectType === '20' ? 'CarrierCore.StartSlotCode' : 'MapCore.StartStation'))
const endExecName = computed(
  () => i18n.t(execForm.value.moveObjectType === '20' ? 'CarrierCore.EndSlotCode' : 'MapCore.EndStation'))
const columns = computed(() => {
  return [{
    column1: { label: i18n.t('TaskCore.CurrentTask'), value: 'taskCode' },
    column2: { label: i18n.t('AGVCore.CurrentSpeed'), value: 'agvSpeed', unit: 'mm/s' }
  }, {
    column1: { label: i18n.t('CreationTime'), value: 'createdTime', format: 'HH:mm:ss YYYY-MM-DD' },
    column2: { label: i18n.t('StartTime'), value: 'execBeginTime', format: 'HH:mm:ss YYYY-MM-DD' }
  }, {
    column1: { label: i18n.t('CarrierCore.RackCode'), value: 'shelvesCode' },
    column2: { label: i18n.t('CarrierCore.ContainerCode'), value: 'containerCode' }
  }, {
    column1: { label: startName.value, value: 'startValue' },
    column2: { label: endName.value, value: 'endValue' }
  }, {
    column1: { label: i18n.t('ErrorMsg'), value: 'originalWarnDesc' },
    column2: { label: `${i18n.t('AGVCore.RegIP')}`, value: 'agvIp' }
  }]
})

watch([() => amrPanel.value.visible, () => amrPanel.value.agvCode], () => {
  execForm.value = { moveObjectType: execForm.value.moveObjectType }
  amrPanel.value.visible && initPopupPosition()
})
onUnmounted(() => (amrPanel.value = { visible: false }))
const formatLabel = col => {
  const value = taskInfo.value[col.value]
  if (col.value === 'startValue') {
    return taskInfo.value.moveObjectType === '20' ? taskInfo.value.startStorageCode : taskInfo.value.startPositionCode
  }
  if (col.value === 'endValue') {
    return taskInfo.value.moveObjectType === '20' ? taskInfo.value.endStorageCode : taskInfo.value.endPositionCode
  }
  if (col.unit) return Math.round((value || 0) * 100) / 100
  if (col.format) return value ? date.formatDate(value, col.format) : value
  return value
}
const handleTask = () => {
  taskCode.value = taskInfo.value.taskCode
  modalVisible.value = true
}
const initPopupPosition = () => {
  const { evt = {} } = amrPanel.value || {}
  popupPosition.value = { top: `${evt.layerY}px`, left: `${evt.layerX}px` }
}
const handleMove = () => {
  if (!startInputRef.value || !startInputRef.value.validate()) return
  if (!endInputRef.value || !endInputRef.value.validate()) return
  if (!codeInputRef.value || !codeInputRef.value.validate()) return
  const { agvCode, agvBrandCode } = taskInfo.value
  handleDispatch('/yfagv/api/mainBusinessLevel3/createSimpleTwoPointTask', { agvCode, agvBrandCode, ...execForm.value })
}
const handleDispatch = (uri, params) => {
  loading.value = true
  const { agvCode, taskCode, agvBrandCode } = taskInfo.value || {}
  postAPI(uri, params || { agvCode, taskCode, agvBrandCode, cancelSameGroupTask: '0' }, () => {
    createSuccessTips({ title: i18n.t('MapCore.AMRSchedulingSucceeded') })
    loading.value = false
  }, () => {
    loading.value = false
  })
}
const handleCancel = () => {
  const msg = i18n.t('TaskCore.CancelTaskTips')
  createDialog({ msg }, () => handleDispatch('/yfagv/api/mainBusinessLevel3/cancelTask2'), () => {})
}
const handleNext = () => {
  const msg = i18n.t('TaskCore.ContinueNextTips')
  createDialog({ msg }, () => handleDispatch('/yfagv/api/mainBusinessLevel3/continueTask2'), () => {})
}
</script>

<style lang="scss" scoped>
.q-field:deep(.q-field__after) {
  padding-left: .125rem;
}

.q-field:deep(.q-radio--dense .q-radio__label) {
  padding-left: 0.25rem;
}

.header-label {
  width: 4.25rem;
}
</style>